package com.v1.video.fragment;

import android.app.Activity;
import android.app.Dialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.iss.view.common.ToastAlone;
import com.iss.view.pulltorefresh.PullToRefreshBase;
import com.iss.view.pulltorefresh.PullToRefreshBase.Mode;
import com.iss.view.pulltorefresh.PullToRefreshBase.OnRefreshListener2;
import com.iss.view.pulltorefresh.PullToRefreshListView;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.tencent.mm.sdk.modelmsg.SendMessageToWX;
import com.tencent.mm.sdk.modelmsg.WXMediaMessage;
import com.tencent.mm.sdk.modelmsg.WXVideoObject;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.umeng.analytics.MobclickAgent;
import com.v1.video.Constant;
import com.v1.video.R;
import com.v1.video.activity.BaseActivity;
import com.v1.video.activity.SharePlatformActionListener;
import com.v1.video.activity.SharePlatformActionListener.SharePlatformCallback;
import com.v1.video.adapter.ClassifyAdapter2;
import com.v1.video.db.dao.VideoTB;
import com.v1.video.db.service.VideoDB;
import com.v1.video.domain.LoginInfo;
import com.v1.video.domain.VideoEntity;
import com.v1.video.domain.VideoPlayEntity;
import com.v1.video.domain.VideoPlayEntity.VideoPlay;
import com.v1.video.engine.NetEngine;
import com.v1.video.engine.RequestEngine;
import com.v1.video.httpmanager.ParamList;
import com.v1.video.httpmanager.ParamList.Parameter;
import com.v1.video.httpmanager.RequestManager;
import com.v1.video.httpmanager.RequestManager.OnResponseListener;
import com.v1.video.util.Helper;
import com.v1.video.util.Logger;
import com.v1.video.util.Utils;
import com.v1.video.view.CustomShareSheetDialog;
import com.v1.video.view.CustomShareSheetDialog.OnShareSheetItemClick;

import java.util.ArrayList;
import java.util.List;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.Platform.ShareParams;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.tencent.qzone.QZone;

/**
 * 频道分类
 * 
 * @author wangfang
 * 
 */
public class ClassifyFragment extends V1BaseFragment {

	private static final String TAG = "ClassifyFragment";
	private View mView, mEmptyView;
	private ListView mListView;
	private TextView mTvTip;;
	private PullToRefreshListView mRefreshListView;
	private ClassifyAdapter2 mAdapter;
	private String mCid;
	private String mType;
	private List<VideoTB> mLstData;
	private int mCurIndex = 0;
	private LayoutInflater mInflater;
	private CustomShareSheetDialog mSharedialog;
	private IWXAPI mWxApi;
	private boolean isLoad = true;
	private int mLstPosition = -1;
	private int mLstVisitbleCount = -1;

	public static ClassifyFragment newInstance(String tag, String type) {
		ClassifyFragment f = new ClassifyFragment();
		Bundle bundle = new Bundle();
		bundle.putString("tag", tag);
		bundle.putString("type", type);
		f.setArguments(bundle);
		return f;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		mInflater = inflater;
		mView = inflater.inflate(R.layout.fragment_classify, container, false);
		initView();
		setListener();
		initData();
		return mView;
	}

	@Override
	public void onResume() {
		super.onResume();
		MobclickAgent.onPageStart("首页-频道");
		resumePlayer();
	}

	@Override
	public void onPause() {
		super.onPause();
		MobclickAgent.onPageEnd("首页-频道");
		pausePlayer();
	}

	@Override
	public void refresh(Object tag) {
		// TODO Auto-generated method stub
		super.refresh(tag);
		if (isLoad == true) {
			isLoad = false;
			if (mRefreshListView != null) {
				mRefreshListView.doPullRefreshing(50);
			}
		}
	}

	@Override
	public void setUserVisibleHint(boolean isVisibleToUser) {
		// TODO Auto-generated method stub
		super.setUserVisibleHint(isVisibleToUser);
		Logger.i(TAG, "setUserVisibleHint--" + isVisibleToUser + "--" + mCid);
		if (!isVisibleToUser) {
			releasePlayer();
		}
	}

	private void initView() {
		mEmptyView = mInflater.inflate(R.layout.fragment_no_content, null);
		mTvTip = (TextView) mView.findViewById(R.id.tv_tip);
		mRefreshListView = (PullToRefreshListView) mView
				.findViewById(R.id.lv_listView);
		mListView = mRefreshListView.getRefreshableView();
		mRefreshListView.setScrollingWhileRefreshingEnabled(false);
		mRefreshListView.setMode(Mode.PULL_FROM_START);
		mType = getArguments().getString("type");
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	private void setListener() {

		mEmptyView.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (mRefreshListView != null) {
					mRefreshListView.doPullRefreshing(100);
				}
			}
		});
		mRefreshListView.setOnRefreshListener(new OnRefreshListener2() {

			@Override
			public void onPullDownToRefresh(PullToRefreshBase refreshView) {
				// TODO Auto-generated method stub
				mCurIndex = 0;
				if (Helper.checkConnection(getActivity())) {
					getServerData();
				} else {
					getLocalData();
				}
			}

			@Override
			public void onPullUpToRefresh(PullToRefreshBase refreshView) {
				// TODO Auto-generated method stub
				if (Helper.checkConnection(getActivity())) {
					getServerData();
				} else {
					getLocalData();
				}
			}
		});

		mListView.setOnScrollListener(new OnScrollListener() {

			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				// TODO Auto-generated method stub
				switch (scrollState) {
				case OnScrollListener.SCROLL_STATE_IDLE:
					ImageLoader.getInstance().resume();
					if (mAdapter != null && mAdapter.getCurIndex() != -1) {
						Logger.i(TAG, "CurIndex=" + mAdapter.getCurIndex());
						int index = mAdapter.getCurIndex() + 1;
						if (mLstPosition > index
								|| index > mLstPosition + mLstVisitbleCount - 1) {
							releasePlayer();
						}
					}
					break;
				case OnScrollListener.SCROLL_STATE_TOUCH_SCROLL:
					ImageLoader.getInstance().pause();
					break;
				case OnScrollListener.SCROLL_STATE_FLING:
					ImageLoader.getInstance().pause();
					break;
				}
			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				// TODO Auto-generated method stub
				Logger.i(TAG, "firstVisibleItem=" + firstVisibleItem
						+ "--visibleItemCount=" + visibleItemCount
						+ "--totalItemCount=" + totalItemCount);
				try {
					mLstPosition = firstVisibleItem;
					mLstVisitbleCount = visibleItemCount;
					if (firstVisibleItem != oldPosition) {
						if (oldPosition != -1 && oldPosition > firstVisibleItem) {
							Logger.i(TAG, "下拉执行");
							if (mAdapter == null || mAdapter.getLst() == null) {
								return;
							}
							if (firstVisibleItem >= mAdapter.getLst().size()) {
								return;
							}
							VideoTB video = mAdapter.getLst().get(
									firstVisibleItem);
							Logger.i(TAG, "video.at=" + video.getAt());
							if (Constant.VIDEO_TYPE_8.equals(video.getAt())) {
								oldTid = video.getTid();
								// if(oldTid.equals("") ||
								// !oldTid.equals(video.getTid())){
								RequestEngine request = new RequestEngine();
								request.sendADVLogToServer(
										getActivity(),
										Constant.STATE_ADV_CZBM_2 + "",
										Constant.STATE_ADV_CZSX_3 + "_"
												+ video.getTid(), ""
												+ Constant.STATE_ADV_CZJG_1);
								// }
								if (firstVisibleItem == 1
										|| firstVisibleItem == 5
										|| firstVisibleItem == 8) {
									String adid = (firstVisibleItem + 1) + "";
									new NetEngine().AdUpToServer(getActivity(),
											video.getAdid(), LoginInfo
													.getInstance().getUserId(),
											adid, "1",mCid);
								}
							}
							oldPosition = firstVisibleItem;
						} else {
							// if (firstVisibleItem == 0) {
							if (oldPosition == firstVisibleItem) {
								return;
							}
							oldPosition = firstVisibleItem;
							int index = firstVisibleItem;
							boolean isHasAdv = false;
							if (mAdapter == null || mAdapter.getLst() == null) {
								return;
							}
							for (int i = 0; i < visibleItemCount; i++) {

								Logger.i(TAG, "上拉执行");
								if (index >= mAdapter.getLst().size()) {
									return;
								}
								if (index < 0) {
									return;
								}
								VideoTB video = mAdapter.getLst().get(index);
								Logger.i(TAG, "video.at===" + video.getAt());
								if (Constant.VIDEO_TYPE_8.equals(video.getAt())) {
									isHasAdv = true;
									Logger.i(TAG,
											"video.getTid()==" + video.getTid()
													+ "oldTid=" + oldTid);
									if (oldTid.equals("")
											|| !oldTid.equals(video.getTid())) {
										RequestEngine request = new RequestEngine();
										request.sendADVLogToServer(
												getActivity(),
												Constant.STATE_ADV_CZBM_2 + "",
												Constant.STATE_ADV_CZSX_3 + "_"
														+ video.getTid(),
												"" + Constant.STATE_ADV_CZJG_1);
										oldTid = video.getTid();
										if (video.getAdShow() != null
												&& video.getAdShow().length() > 5) {
											RequestEngine request1 = new RequestEngine();
											request1.askThirdADVLink(
													getActivity(),
													video.getAdShow());
										}
										if (index == 1
												|| index == 5
												|| index == 8) {
											String adid = (index + 1) + "";
											new NetEngine().AdUpToServer(getActivity(),
													video.getAdid(), LoginInfo
															.getInstance().getUserId(),
													adid, "1",mCid);
										}
									}
								}
								++index;
							}
							if (!isHasAdv) {
								oldTid = "";
							}
						}
					}
				} catch (Exception ex) {
					ex.printStackTrace();
				}
			}
		});
	}

	int oldPosition = -1;
	String oldTid = "";

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == Constant.REQUESTCODE_FULL_SCREEN) {
			if (resultCode == Activity.RESULT_OK) {
				int position = data.getIntExtra("position", 0);
				if (position > 0) {
					if (mAdapter != null) {
						mAdapter.setCurPosition(position);
						mAdapter.resumePlayer();
					}
				} else {
					if (mAdapter != null) {
						mAdapter.releasePlayer();
					}
				}
			}
		}
	}

	private void initData() {
		mCid = getArguments().getString("tag");
		mWxApi = WXAPIFactory.createWXAPI(this.getActivity(), Constant.APP_ID);
		mWxApi.registerApp(Constant.APP_ID);
		clickStatistics(Constant.HOME_CLASSIFICATION_ID, "首页频道-" + mCid);
		mAdapter = new ClassifyAdapter2(getActivity());
		mAdapter.setParentFragment(ClassifyFragment.this);
		mAdapter.setmType(mType);
		mAdapter.setCid(mCid);
		mAdapter.setHandler(mHandler);
		mListView.setAdapter(mAdapter);
	}

	/**
	 * 显示提示信息
	 * 
	 * @param text
	 */
	private void showTip(String text) {
		mTvTip.setText(text);
		mTvTip.setVisibility(View.VISIBLE);
		Animation anim = AnimationUtils.loadAnimation(getActivity(),
				R.anim.trans_tip_out);
		mTvTip.startAnimation(anim);
		mTvTip.postDelayed(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				mTvTip.setVisibility(View.GONE);
			}
		}, 2000);
	}

	/**
	 * 设置空的界面显示
	 */
	private void setEmptyView() {
		if (mCurIndex == 0) {
			View view = mListView.getEmptyView();
			if (view == null) {
				mListView.setEmptyView(mEmptyView);
			}
			if (mRefreshListView != null) {
				mRefreshListView.setMode(Mode.PULL_FROM_START);
			}
		}
	}

	private void getLocalData() {

		mHandler.post(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				mLstData = VideoDB.getInstance().getSingleQuery(mCid,
						mCurIndex, Constant.HOME_WATERFULL_PAGE_SIZE);
				if (mRefreshListView != null) {
					mRefreshListView.onRefreshComplete();
				}
				if (mLstData != null && mLstData.size() > 0) {
					if (mLstData.size() < Constant.HOME_WATERFULL_PAGE_SIZE) {
						if (mRefreshListView != null) {
							mRefreshListView.setMode(Mode.PULL_FROM_START);
						}
					} else {
						if (mRefreshListView != null) {
							mRefreshListView.setMode(Mode.BOTH);
						}
					}
					if (mCurIndex == 0) {
						if (mAdapter != null) {
							mAdapter.setLstData(mLstData);
						}
					} else {
						if (mAdapter != null) {
							mAdapter.setAddLstData(mLstData);
						}
					}
					mCurIndex++;
				} else {
					setEmptyView();
				}
			}
		});
	}

	/**
	 * 获取服务器其他频道列表数据
	 */
	private void getServerData() {
		String url = String.format(Constant.HOME_CLASSIFY_LIST, mCid,
				mCurIndex, Constant.PRODUCT_CODE, Constant.PRODUCT_VERSION,
				Constant.DEVICEID);
		Logger.i(TAG, "其他频道url==" + url);
		RequestManager.getInstance().getRequest(this.getActivity(), url,
				VideoEntity.class, mCid, new OnResponseListener() {

					@Override
					public void onSuccess(Object object, int code,
							String message, String keyId) {
						// TODO Auto-generated method stub
						try {
							if (object != null) {
								VideoEntity entity = (VideoEntity) object;
								if (entity != null
										&& entity.getBody() != null
										&& entity.getBody().getData() != null
										&& entity.getBody().getData().size() > 0) {
									getSplicingData(entity.getBody().getData(),
											entity.getBody().getRefresh_num());
								} else {
									if (mRefreshListView != null) {
										mRefreshListView.onRefreshComplete();
									}
									setEmptyView();
								}
							} else {
								if (mRefreshListView != null) {
									mRefreshListView.onRefreshComplete();
								}
								setEmptyView();
							}
						} catch (Exception ex) {
							ex.printStackTrace();
						}
					}

					@Override
					public void onFailure(int code, String message) {
						// TODO Auto-generated method stub
						if (mRefreshListView != null) {
							mRefreshListView.onRefreshComplete();
						}
						setEmptyView();
						// showToast(message);
						Logger.i(TAG, message);
					}
				});
	}

	/**
	 * 获取服务器播放次数列表数据
	 * 
	 * @param mLst
	 * @param refreshNum
	 */
	private void getSplicingData(final List<VideoTB> mLst,
			final String refreshNum) {
		StringBuilder sbuilder = new StringBuilder();
		for (int i = 0; i < mLst.size(); i++) {
			VideoTB videoTb = mLst.get(i);
			if (videoTb != null && !TextUtils.isEmpty(videoTb.getVid())) {
				if (sbuilder.length() > 0) {
					sbuilder.append(",");
				}
				sbuilder.append(videoTb.getVid());
			}
		}
		String url = String.format(Constant.HOME_CLASSIFY_PALY_LIST,
				Constant.PRODUCT_CODE, Constant.PRODUCT_VERSION,
				Constant.DEVICEID);
		ParamList params = new ParamList();
		params.add(new Parameter("vids", sbuilder.toString()));
		Logger.i(TAG, "其他频道播放次数url=" + url + "&vids=" + sbuilder.toString());
		RequestManager.getInstance().postRequest(this.getActivity(), url,
				params, VideoPlayEntity.class, mCid, new OnResponseListener() {

					@Override
					public void onSuccess(Object object, int code,
							String message, String keyId) {
						// TODO Auto-generated method stub
						if (mRefreshListView != null) {
							mRefreshListView.onRefreshComplete();
						}
						try {
							if (object != null) {
								VideoPlayEntity entity = (VideoPlayEntity) object;
								if (entity != null && entity.getBody() != null
										&& entity.getBody().getData() != null) {
									List<VideoTB> videoLst = new ArrayList<VideoTB>();
									videoLst.addAll(mLst);
									List<VideoPlay> playLst = entity.getBody()
											.getData();
									if (videoLst != null && videoLst.size() > 0
											&& playLst != null
											&& playLst.size() > 0) {
										for (int i = 0; i < videoLst.size(); i++) {
											VideoTB videoTb = videoLst.get(i);
											if (!TextUtils.isEmpty(videoTb
													.getVid())) {
												for (int j = 0; j < playLst
														.size(); j++) {
													VideoPlay play = playLst
															.get(j);
													if (play != null
															&& videoTb
																	.getVid()
																	.equals(play
																			.getVideoId())) {
														videoTb.setPlayNum(play
																.getPlayNum());
														videoTb.setLikeNum(play
																.getLikeNum());
														videoTb.setShareNum(play
																.getShareNum());
													}
												}
											}
										}
										if (mCurIndex == 0
												&& !TextUtils
														.isEmpty(refreshNum)
												&& !refreshNum.equals("0")) {
											showTip(String.format(
													Constant.MESSAGE_UPDATA,
													refreshNum));
											int index = Integer
													.parseInt(refreshNum) - 1;
											if (mAdapter != null) {
												mAdapter.setIndex(index);
											}
										} else {
											if (mAdapter != null) {
												mAdapter.setIndex(-1);
											}
										}
										boolean isDel = false;
										if (mAdapter != null) {
											mAdapter.releasePlayer();
											if (mCurIndex == 0) {
												mAdapter.setLstData(videoLst);
												isDel = true;
											} else {
												mAdapter.setAddLstData(videoLst);
											}
											Message msg = mHandler
													.obtainMessage();
											msg.what = Constant.CLASSIFY_ADV;
											mHandler.sendMessage(msg);
										}

										if (mCurIndex < Constant.WATERFULL_PAGE) {
											mCurIndex++;
											if (mRefreshListView != null) {
												mRefreshListView
														.setMode(Mode.BOTH);
											}
										} else {
											if (mRefreshListView != null) {
												mRefreshListView
														.setMode(Mode.PULL_FROM_START);
											}
										}
										saveLocalData(videoLst, isDel);
										requestExposure(videoLst);
									}
								} else {
									setEmptyView();
								}
							} else {
								setEmptyView();
							}
						} catch (Exception ex) {
							ex.printStackTrace();
						}
					}

					@Override
					public void onFailure(int code, String message) {
						// TODO Auto-generated method stub
						if (mRefreshListView != null) {
							mRefreshListView.onRefreshComplete();
						}
						setEmptyView();
						// showToast(message);
						Logger.i(TAG, message);
					}
				});
	}

	private void saveLocalData(List<VideoTB> videoLst, boolean isDel) {
		try {
			if (isDel == true) {
				VideoDB.getInstance().deleteAll();
			}
			if (videoLst != null && videoLst.size() > 0) {
				VideoDB.getInstance().insertInTx(videoLst);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private Handler mHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			switch (msg.what) {
			case Constant.CLASSIFY_REFRESH:
				if (mRefreshListView != null) {
					mRefreshListView.doPullRefreshing(100);
				}
				break;
			case Constant.CLASSIFY_PRAISE:
				break;
			case Constant.CLASSIFY_SHARE:
				break;
			case Constant.CLASSIFY_ADV:
				Logger.i(TAG, "handler_Constant.CLASSIFY_ADV="
						+ Constant.CLASSIFY_ADV);
				Logger.i(TAG, "mLstVisitbleCount==" + mLstVisitbleCount);
				try {
					int index = 0;
					if (mAdapter == null || mAdapter.getLst() == null) {
						return;
					}
					for (int i = 0; i < mLstVisitbleCount; i++) {
						if (i >= mAdapter.getLst().size()) {
							return;
						}
						if (index < 0) {
							return;
						}
						Logger.i(TAG, "上拉执行");
						VideoTB video = mAdapter.getLst().get(index);
						Logger.i(TAG, "video.at===" + video.getAt());
						if (Constant.VIDEO_TYPE_8.equals(video.getAt())) {
							Logger.i(TAG, "video.getTid()==" + video.getTid()
									+ "oldTid=" + oldTid);
							if (oldTid.equals("")
									|| !oldTid.equals(video.getTid())) {
								RequestEngine request = new RequestEngine();
								request.sendADVLogToServer(
										getActivity(),
										Constant.STATE_ADV_CZBM_2 + "",
										Constant.STATE_ADV_CZSX_3 + "_"
												+ video.getTid(), ""
												+ Constant.STATE_ADV_CZJG_1);
								oldTid = video.getTid();
								if (video.getAdShow() != null
										&& video.getAdShow().length() > 5) {
									RequestEngine request1 = new RequestEngine();
									request1.askThirdADVLink(getActivity(),
											video.getAdShow());
								}
							}
						}
						++index;
					}
				} catch (Exception e) {
					// TODO: handle exception
					e.printStackTrace();
				}
				break;
			default:
				break;
			}
		}
	};

	/**
	 * 请求曝光
	 * 
	 * @param videoLst
	 */
	private void requestExposure(List<VideoTB> videoLst) {
		if (videoLst != null) {
			for (int i = 0; i < videoLst.size(); i++) {
				VideoTB videoTb = videoLst.get(i);
				if (videoTb != null && !TextUtils.isEmpty(videoTb.getAt())
						&& Constant.VIDEO_TYPE_8.equals(videoTb.getAt())) {
					if (!TextUtils.isEmpty(videoTb.getAdShow())) {
						RequestManager.getInstance().getRequest(
								ClassifyFragment.this.getActivity(),
								videoTb.getAdShow());
					}
				}
			}
		}
	}

	private void resumePlayer() {
		if (mAdapter != null) {
			mAdapter.resumePlayer();
		}
	}

	/**
	 * 释放视频播放器资源
	 */
	private void pausePlayer() {
		if (mAdapter != null) {
			mAdapter.pausePlayer();
		}
	}

	/**
	 * 释放视频播放器资源
	 */
	public void releasePlayer() {
		if (mAdapter != null) {
			mAdapter.releasePlayer();
		}
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		isLoad = true;
		pausePlayer();
		if (mAdapter != null) {
			mAdapter.releasePlayer();
			mAdapter = null;
		}
		if (mLstData != null) {
			mLstData.clear();
			mLstData = null;
		}
		RequestManager.getInstance().requestCancel(this.getActivity(), mCid);
	}

	@Override
	public void onDestroyView() {
		// TODO Auto-generated method stub
		if (mView != null) {
			((ViewGroup) mView.getParent()).removeView(mView);
		}
		super.onDestroyView();
	}

	/**
	 * 分享
	 * 
	 * @param videoTb
	 */
	public void showShareDialog(final VideoTB videoTb,
			final SharePlatformCallback onSharePlatformCallback) {
		clickStatistics(Constant.SHARE_ID, "频道视频分享");
		mSharedialog = new CustomShareSheetDialog(this.getActivity());
		mSharedialog.setOnShareSheetItemClick(new OnShareSheetItemClick() {

			@Override
			public void onClick(int shareType) {
				if (mSharedialog != null && mSharedialog.isShowing()) {
					mSharedialog.dismiss();
				}
				mSharedialog = null;
				switch (shareType) {
				case CustomShareSheetDialog.TYPE_WEIXIN_MOMENTS:
					if (mWxApi.isWXAppInstalled()) {
						onkeyshareWeiXin(videoTb, 0, onSharePlatformCallback);
					} else {
						showToast("亲，您尚未安装微信客户端，请下载安装~");
					}

					break;
				case CustomShareSheetDialog.TYPE_WEIXIN:
					if (mWxApi.isWXAppInstalled()) {
						onkeyshareWeiXin(videoTb, 1, onSharePlatformCallback);
					} else {
						showToast("亲，您尚未安装微信客户端，请下载安装~");
					}
					break;
				case CustomShareSheetDialog.TYPE_QQ:
					onkeyshareQQ(videoTb, ShareSDK.getPlatform(
							ClassifyFragment.this.getActivity(), QQ.NAME),
							onSharePlatformCallback);
					break;
				case CustomShareSheetDialog.TYPE_QQ_SPACE:
					onkeyshareQQ(videoTb, ShareSDK.getPlatform(
							ClassifyFragment.this.getActivity(), QZone.NAME),
							onSharePlatformCallback);
					break;
				case CustomShareSheetDialog.TYPE_SINA_WEIBO:
					showSharedDialog(ClassifyFragment.this.getActivity(),
							videoTb, 0, onSharePlatformCallback);
					break;
				case CustomShareSheetDialog.TYPE_COPY:
					ClipboardManager c = (ClipboardManager) ClassifyFragment.this
							.getActivity().getSystemService(
									Context.CLIPBOARD_SERVICE);
					if (!TextUtils.isEmpty(videoTb.getShareUrl())) {
						c.setPrimaryClip(ClipData.newPlainText("url",
								videoTb.getShareUrl()));
					} else {
						c.setPrimaryClip(ClipData.newPlainText("url",
								videoTb.getVideoUrl()));
					}
					showToast("复制成功");
					break;
				}

			}
		});
		// }
		mSharedialog.show();
	}

	/** 分享到微信0:朋友圈，1 微信好友 */
	private void onkeyshareWeiXin(VideoTB videoTb, int type,
			SharePlatformCallback onSharePlatformCallback) {
		if (videoTb != null) {
			WXVideoObject video = new WXVideoObject();
			if (!TextUtils.isEmpty(videoTb.getShareUrl())
					&& videoTb.getShareUrl().length() > 6) {
				video.videoUrl = videoTb.getShareUrl();
			} else {
				video.videoUrl = Constant.PAIKE_VIDEO_SHARE_URL
						+ videoTb.getPic() + "&videoURL="
						+ videoTb.getVideoUrl();
			}
			String content = "\""
					+ videoTb.getTitle()
					+ "\""
					+ "点此播放"
					+ "\""
					+ video.videoUrl
					+ "\""
					+ "（通过＃第一视频＃分享，@第一视频，聚合全球海量有趣有料有用的精选短视频，助你大开眼界！下载猛戳http://apps.v1.cn）";
			WXMediaMessage msg = new WXMediaMessage(video);
			msg.title = videoTb.getTitle();
			msg.description = content;
			Bitmap thumb = BitmapFactory.decodeResource(getResources(),
					R.drawable.ic_launcher);
			msg.thumbData = com.v1.video.util.Util.bmpToByteArray(thumb, true);
			SendMessageToWX.Req req = new SendMessageToWX.Req();
			req.transaction = buildTransaction("video");
			req.message = msg;
			req.scene = (type == 0 ? SendMessageToWX.Req.WXSceneTimeline
					: SendMessageToWX.Req.WXSceneSession);
			mWxApi.sendReq(req);
			Constant.setShare(true);
			Constant.listenerShare.init(this.getActivity(),
					onSharePlatformCallback);
		} else {
			showToast("未获取到分享内容");
		}
	}

	private String buildTransaction(final String type) {
		return (type == null) ? String.valueOf(System.currentTimeMillis())
				: type + System.currentTimeMillis();
	}

	/**
	 * QQ空间和QQ
	 * 
	 * @param plat
	 */
	private void onkeyshareQQ(VideoTB videoTb, Platform plat,
			SharePlatformCallback onSharePlatformCallback) {
		if (videoTb != null) {
			String url = "";
			if (!TextUtils.isEmpty(videoTb.getShareUrl())
					&& videoTb.getShareUrl().length() > 6) {
				url = videoTb.getShareUrl();
			} else {
				url = Constant.PAIKE_VIDEO_SHARE_URL + videoTb.getPic()
						+ "&videoURL=" + videoTb.getVideoUrl();
			}
			String content = "\""
					+ videoTb.getTitle()
					+ "\""
					+ "点此播放"
					+ "\""
					+ url
					+ "\""
					+ "（通过＃第一视频＃分享，@第一视频，聚合全球海量有趣有料有用的精选短视频，助你大开眼界！下载猛戳http://apps.v1.cn）";
			ShareParams sp = new ShareParams();
			sp.setShareType(Platform.SHARE_IMAGE);
			sp.setTitle(videoTb.getTitle());
			sp.setTitleUrl(url);
			sp.setText(content);
			sp.setImageUrl(videoTb.getPic());
			plat.setPlatformActionListener(new SharePlatformActionListener(this
					.getActivity(), onSharePlatformCallback));
			plat.share(sp);
		} else {
			showToast("未获取到分享内容");
		}
	}

	/**
	 * 分享弹出框
	 * 
	 * @param context
	 * @param id
	 * @param type
	 *            0:新浪，1，腾讯微博 2，两个一起
	 */
	private void showSharedDialog(final Context context, final VideoTB videoTb,
			final int type, final SharePlatformCallback onSharePlatformCallback) {
		String url = "";
		if (!TextUtils.isEmpty(videoTb.getShareUrl())
				&& videoTb.getShareUrl().length() > 6) {
			url = videoTb.getShareUrl();
		} else {
			url = Constant.PAIKE_VIDEO_SHARE_URL + videoTb.getPic()
					+ "&videoURL=" + videoTb.getVideoUrl();
		}
		String content = "\""
				+ videoTb.getTitle()
				+ "\""
				+ "点此播放"
				+ "\""
				+ url
				+ "\""
				+ "（通过＃第一视频＃分享，@第一视频，聚合全球海量有趣有料有用的精选短视频，助你大开眼界！下载猛戳http://apps.v1.cn）";
		View shareView = View.inflate(context, R.layout.dialog_one_key_share,
				null);
		final Dialog dialog = new Dialog(context, R.style.dialog_custom);
		Display display = this.getActivity().getWindowManager()
				.getDefaultDisplay();
		int width = display.getWidth();
		LayoutParams params = new LayoutParams((int) (width * 0.9),
				ViewGroup.LayoutParams.MATCH_PARENT);
		dialog.setContentView(shareView, params);
		dialog.setCancelable(true);

		final EditText contentEt = (EditText) shareView
				.findViewById(R.id.tv_shared_content);
		final TextView contentNum = (TextView) shareView
				.findViewById(R.id.tv_content_num);

		final View sinaSelect = shareView.findViewById(R.id.rl_sina);
		final View qqSelect = shareView.findViewById(R.id.rl_qq_share);
		contentEt.setText(content);
		if (type == 0) {
			qqSelect.setVisibility(View.GONE);
		} else if (type == 1) {
			sinaSelect.setVisibility(View.GONE);
		}
		if (!content.equals("")) {
			String number = Utils.calculateLength(content) + "/"
					+ BaseActivity.TEXT_LENGTH;
			contentNum.setText(number);
		} else {
			contentNum.setText("0/" + BaseActivity.TEXT_LENGTH);
		}

		contentEt.addTextChangedListener(new TextWatcher() {
			private CharSequence temp;
			private int selectionStart;
			private int selectionEnd;

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				temp = s;
			}

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
			}

			@Override
			public void afterTextChanged(Editable s) {
				String number = Utils.calculateLength(s) + "/"
						+ BaseActivity.TEXT_LENGTH;
				contentNum.setText(number);
				selectionStart = contentEt.getSelectionStart();
				selectionEnd = contentEt.getSelectionEnd();
				if (Utils.calculateLength(temp) > BaseActivity.TEXT_LENGTH) {
					s.delete(
							(selectionStart - (int) (Utils.calculateLength(s) - BaseActivity.TEXT_LENGTH)),
							selectionEnd);
					contentEt.setText(s);
					contentEt.setSelection(selectionStart);// 设置光标
				}
			}
		});

		shareView.findViewById(R.id.tv_share).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View v) {
						String contentStr = contentEt.getText().toString()
								.trim();
						if (!TextUtils.isEmpty(contentStr)) {
							onkeyshare(v, ShareSDK.getPlatform(
									ClassifyFragment.this.getActivity(),
									SinaWeibo.NAME), videoTb, contentStr,
									onSharePlatformCallback);
							dialog.dismiss();

						} else {
							ToastAlone.showToast(
									ClassifyFragment.this.getActivity(),
									R.string.share_content_not_null, 0);
						}
					}
				});
		shareView.findViewById(R.id.close_account_cancel).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View v) {
						dialog.dismiss();
					}
				});
		shareView.findViewById(R.id.iv_cleanup).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View v) {
						contentEt.setText("");
						contentNum.setText("0/" + BaseActivity.TEXT_LENGTH);
					}
				});

		dialog.setOnDismissListener(new OnDismissListener() {

			@Override
			public void onDismiss(DialogInterface dialog) {
				// isCanPlay = true;
			}
		});
		dialog.show();
	}

	/**
	 * sina微博
	 * 
	 * @param v
	 * @param plat
	 * @param content
	 */
	private void onkeyshare(View v, Platform plat, VideoTB videoTb,
			String content, SharePlatformCallback onSharePlatformCallback) {
		if (videoTb != null) {
			ShareParams sp = new ShareParams();
			sp.setShareType(Platform.SHARE_IMAGE);
			sp.setTitle(videoTb.getTitle());
			sp.setText(content);
			sp.setImageUrl(videoTb.getPic()); // 直接分享网络地址
			plat.setPlatformActionListener(new SharePlatformActionListener(
					ClassifyFragment.this.getActivity(),
					onSharePlatformCallback));
			plat.share(sp);
		} else {
			showToast("未获取到标题");
		}
	}
}
